<template>
  <div>
    <el-row :gutter="20">
      <el-col v-for="(device, index) in devicesInfos" :key="index" :span="3">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="width: 150px; height: 20px">
            <span @click="showWaveHistory(device.gwsn)" style="cursor: pointer;">焊机编号: {{ device.colmodel }}</span>
            <!--            <span class="status-dot" :class="device.status == '1' ? 'green' : 'black'" style="display: inline-block; width: 16px; height: 16px; border-radius: 50%; margin-left: 10px;border: red 1px solid">{{device.status}}</span>-->
            <!--            <span class="status-dot" v-bind:class="{'green': device.status == '1', 'black': device.status != '1'}" style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-left: 10px;"></span>-->
          </div>
          <div class="text item">
            <div>
              <!--              <span>运行状态：</span> <span>{{device.status}}</span>-->
              <span>运行状态：</span>
              <div v-if="device.status==='0' || device.status==null" class="statestyle"></div>
              <div v-else-if="device.status==='1'" class="statestyle_2"></div>

            </div>
            <!--          <el-button circle></el-button>-->
          </div>
          <div class="text item" style="width: 150px; height: 40px">
            <div>电压: {{ device.U ? Number(device.U).toFixed(3)+'V' : "0" }}</div>
            <div>电流: {{ device.I && device.U ? (device.I*120).toFixed(3)+'A' : "0" }}</div>
            <div>功率: {{ device.P ? Number(device.P).toFixed(3) : "0" }}</div>
            <div>时间: {{ device.time ? device.time : getCurrentDateTime() }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <weldingmachineinfo v-if="Visiable" ref="weldingmachineinfodialog"></weldingmachineinfo>
    <wavehistory v-if="Visiable" ref="wavehistorydialog"></wavehistory>
  </div>
</template>

<script>
import $ from 'jquery'
import * as echarts from 'echarts';
import statepop from './statepop'
import Statepop from './statepop'
import weldingmachineinfo from './weldingmachineinfo'
import Wave from './wave'
import wavehistory from './wavehistory'
import Vue from 'vue'

export default {
  components: {
    Wave,
    Statepop,
    weldingmachineinfo,
    wavehistory
  },
  data () {
    return {
      dataForm: {
        key: ''
      },
      deviceInfos: [],
      dataList: [],
      dataList1: [{}],
      dataJson: {

      },
      dataJson1: [],
      alarmNum: 0,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      radio: '11',
      Visiable: false,
      devices: {},
      devicesInfos:{},
      websocket: null
    }
  },
  computed:{
    // filter(){
    //   return this.stateList.filter((item) => {
    //     return item.indexOf(this.radio) !== -1
    //   })
    // }
  },
  created () {
  },
  mounted () {
    this.getWeldingMachineInfo()
    this.connectToWebSocket()

  },
  updated () {

  },
  activated () {

  },
  methods: {
    //获取当前时间
    getCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');  // 0-based month
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      const second = String(now.getSeconds()).padStart(2, '0');


      return `${year}${month}${day}${hour}${minute}${second}`;
    },
    // 获取数据列表
    getWeldingMachineInfo () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/weldingmachineinfo/weldingmachineinfo/getwminfo'),
        method: 'get',
        params: this.$http.adornParams({
          'wmId': this.dataForm.wmId,
          'wmNote': this.dataForm.wmNote
        })
      }).then(({data}) => {
        console.log(data)
        this.devicesInfos = data;
        this.dataListLoading = false
      })
    },
    connectToWebSocket() {
      //1：在methods中写一个方法，用于连接webSocket，URL就是后端提供的接口地址：ws://10.143.7.73:8089/renren-fast/websocket/mqtt
      this.websocket = new WebSocket("ws://10.143.7.73:8089/renren-fast/websocket/mqtt");
      // this.websocket = new WebSocket("ws://101.43.150.26:8089/renren-fast/websocket/mqtt");
      // this.websocket = new WebSocket("ws://10.143.7.73:8089/renren-fast/websocket/mqtt");
      //2：连接成功，获取后端推送的数据信息
      this.websocket.onmessage = (event) => {
        let receivedData = JSON.parse(event.data);
        // console.log(receivedData)
        //这里的receivedData就是后端推送过来的数据
        //3：从推送的数据中找到设备的状态数据，更新到你需要更新的设备状态处，
        if ("wmNo" in receivedData) {
          // console.log("---------2-----------")
          // console.log(receivedData) 此时的receivedData格式为：{"wmNo":"20","gatew":"12304178610183","status":"0"}
          // console.log("----------2----------")
          // 根据 receivedData 中的 gwsn 查找对应的设备信息
          let deviceIndex = this.devicesInfos.findIndex((device) => device.gwsn == receivedData.gatew);
          if (deviceIndex !== -1) {
            // 更新设备信息的属性
            Vue.set(this.devicesInfos[deviceIndex], 'status', receivedData.status);
          }
          // this.handleDevice1Data(receivedData);
        }if (receivedData.status==1) {//4：从推送的数据中找到设备数据，更新到设备数据处，
          // console.log( receivedData)
          //console.log(receivedData) 此时的receivedData格式为：{"type":"data","time":"20230829112715","datatime":"20230829112700","gwSN":"12304178610198","meterSN":"12304178610326","meterName":"DJSF1352RN","meterStatus":"normal","ch":0,"U":0,"I":1.014,"P":0,"TEMP":34.3,"EPI":14.042,"EPE":0,"PT":1,"CT":5}
          // 根据 receivedData 中的 gwsn 查找对应的设备信息
          let deviceIndex = this.devicesInfos.findIndex((device) => device.gwsn == receivedData.gwsn);
          if (deviceIndex !== -1) {//deviceIndex为-1，表示没有找到对应的设备信息
            // 更新设备信息的属性
            console.log("渲染")
            Vue.set(this.devicesInfos[deviceIndex], 'U', receivedData.U);
            Vue.set(this.devicesInfos[deviceIndex], 'I', receivedData.I);
            Vue.set(this.devicesInfos[deviceIndex], 'P', receivedData.P);
            Vue.set(this.devicesInfos[deviceIndex], 'time', receivedData.time);
          }
        } else {
          // 处理其他设备类型的数据
        }

      };

      //连接成功的显示
      this.websocket.onopen = (event) => {
        console.log("WebSocket is open now.");
      };
      //
      this.websocket.onerror = (event) => {
        console.log("WebSocket error observed:", event);
      };
    },
    closeWebSocket() {
      this.websocket.close();
    },
    // showWeldingMachineInfo(gwSN){
    //   console.log(gwSN)
    //   this.Visiable = true;
    //   this.$nextTick(() => {
    //     this.$refs.weldingmachineinfodialog.init(gwSN);
    //   })
    // },
    showWaveHistory(gwSN){
      console.log(gwSN)
      this.Visiable = true;
      this.$nextTick(() => {
        this.$refs.wavehistorydialog.init(gwSN);
      })
    },
  },

}
</script>

<style lang="scss">
.statestyle{
  width:16px;
  height:16px;
  //border: solid 1px black;
  display: inline;
  float: right;
  border-radius: 50%;
  background-color: black
}
.statestyle_2{
  width:16px;
  height:16px;
  display: inline;
  float: right;
  border-radius: 50%;
  background-color: green;
}
.statestyle_3{
  width:20px;
  height:20px;
  border: solid 1px black;
  display: inline;
  float: right;
  border-radius: 50%;
  background-color: skyblue;
}
.text {
  font-size: 10px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: 150px;
  //height: 200px;
}
.mod-home {
  line-height: 1.5;
}
.mod-demo-echarts {
  > .el-alert {
    margin-bottom: 10px;
  }
  > .el-row {
    margin-top: -10px;
    margin-bottom: -10px;
    .el-col {
      padding-top: 10px;
      padding-bottom: 10px;
    }
  }
  .chart-box {
    min-height: 400px;
  }
  .dotClass {
    width:10px;
    height:10px;
    border-radius: 50%;
    display: block;
    margin-left: 10px;  //这个用于圆点居中
  }
  .box-card .status-dot {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-left: 10px;
    border: red 1px solid;
  }

  .green {
    background-color: green;
  }

  .black {
    background-color: black;
  }
}
</style>

